package com.ktjiaoyu.server.config.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //判断当前访问的资源所需要的角色和当前用户所拥有角色是否匹配
        for (ConfigAttribute configAttribute : collection) {//遍历所访问的资源所需要的角色
            String needRole=configAttribute.getAttribute();
            //1.判断是不是只要登录就可以
            if("ROLE_LOGIN".equals(needRole)){
                //判断是否登录
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("尚未登录，请登录!");
                }else{//登录了
                    return;
                }
            }
            //2.登录并且还需要拥有指定的角色
            Collection<? extends GrantedAuthority> authorities =
                    authentication.getAuthorities();
            if(authorities!=null){
                for (GrantedAuthority authority : authorities) {
                    if(authority.getAuthority().equals(needRole)){
                        return;
                    }
                }
            }
        }
        // 如果上述整体都不行的话，那就抛出异常
        throw new AccessDeniedException("权限不足，请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
